package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.CouponInfo;
import logic.util.Utils;


/**
 * OrderMenuUseCouponActivity
 *
 * @Description 使用代金券界面
 * @Author zhangdong
 * @Date 2015年7月14日上午11:03:06
 */
public class OrderMenuUseCouponActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener {
    private Context context;
    private LoadingView loadingView;
    private TextView tvTitle;
    private Button btnBack, btnSure;
    private LinearLayout llBody, llEmpty, llSingle, llMulti;
    private ListView lvSingle, lvMulti;
    private int money, posi = 0;
    private long discount;
    private List<CouponInfo> listCoupons = new ArrayList<CouponInfo>();
    private List<CouponInfo> singleCoupons = new ArrayList<CouponInfo>();
    private List<CouponInfo> multiCoupons = new ArrayList<CouponInfo>();
    private SingleAdapter singleAdapter = new SingleAdapter();
    private MultiAdapter multiAdapter = new MultiAdapter();
    private ArrayList<String> listSelected;
    private boolean singleMode, multiMode = false;
    private List<CouponInfo> selectedCoupons = new ArrayList<CouponInfo>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = this;
        setContentView(R.layout.om_use_coupon);
        initView();
        initLoadingView();
        initData();
        setListener();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

            }
        }
    };

    private void setListener() {
        btnBack.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        lvSingle.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RadioButton rbCoupon = (RadioButton) view.findViewById(R.id.rb_om_use_coupon_single);
                if (!rbCoupon.isEnabled()) return;
                if (rbCoupon.isChecked()) {
                    rbCoupon.setChecked(false);
                    posi = 10000;
                    discount = 0;
                    singleMode = false;
                } else {
                    rbCoupon.setChecked(true);
                    posi = position;
                    discount = singleCoupons.get(position).getCardPrice();
                    singleMode = true;
                    multiMode = false;
                    selectedCoupons.clear();
                    selectedCoupons.add(singleCoupons.get(position));
                    for (int i = 0; i < multiCoupons.size(); i++) {
                        listSelected.set(i, "false");
                    }
                }
                singleAdapter.notifyDataSetChanged();
                multiAdapter.notifyDataSetChanged();
            }
        });
        lvMulti.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox cbCoupon = (CheckBox) view.findViewById(R.id.cb_om_use_coupon_multi);
                if (cbCoupon.isEnabled()) {
                    if (cbCoupon.isChecked()) {
                        cbCoupon.setChecked(false);
                        discount -= multiCoupons.get(position).getCardPrice();
                        listSelected.set(position, "false");
                    } else {
                        if (posi != 10000) {
                            discount = 0;
                            posi = 10000;
                            singleMode = false;
                        }
                        cbCoupon.setChecked(true);
                        discount += multiCoupons.get(position).getCardPrice();
                        listSelected.set(position, "true");
                    }
                    multiMode = false;
                    for (int i = 0; i < listSelected.size(); i++) {
                        if (listSelected.get(i).equals("true")) {
                            multiMode = true;
                            break;
                        }
                    }
                    multiAdapter.notifyDataSetChanged();
                    singleAdapter.notifyDataSetChanged();
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("使用代金券");
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);

        llBody = (LinearLayout) findViewById(R.id.ll_om_use_coupon_body);
        loadingView = (LoadingView) findViewById(R.id.order_loading_view);
        llEmpty = (LinearLayout) findViewById(R.id.ll_om_use_coupon_empty);
        llBody.setVisibility(View.GONE);
        loadingView.setVisibility(View.VISIBLE);
        llEmpty.setVisibility(View.GONE);

        llSingle = (LinearLayout) findViewById(R.id.ll_om_use_coupon_single);
        lvSingle = (ListView) findViewById(R.id.lv_om_use_coupon_single);
        llMulti = (LinearLayout) findViewById(R.id.ll_om_use_coupon_multi);
        lvMulti = (ListView) findViewById(R.id.lv_om_use_coupon_multi);
        llSingle.setVisibility(View.VISIBLE);
        llMulti.setVisibility(View.VISIBLE);

        btnSure = (Button) findViewById(R.id.common_header_commit);
        btnSure.setText("确定");
        btnSure.setBackgroundResource(R.drawable.order_seat_foot_button_selector);
        btnSure.setTextColor(Color.parseColor("#ffffff"));
        btnSure.setVisibility(View.GONE);
    }

    private void initLoadingView() {
        loadingView.setLoadingAnim(R.drawable.home_progress);
        loadingView.changeLoadingStatus(0);
    }

    private void initData() {
        money = (int) getIntent().getDoubleExtra("money", 0);
        posi = getIntent().getIntExtra("position", 10000);
        discount = getIntent().getLongExtra("discount", 0);
        listSelected = getIntent().getStringArrayListExtra("selected");
        NewActionHelp.qryUserVoucherList(context, 1, new QryCouponsHandler());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                this.finish();
                break;
            case R.id.common_header_commit:
                Intent intent = new Intent();
                intent.putExtra("position", posi);
                intent.putExtra("discount", discount);
                intent.putStringArrayListExtra("selected", listSelected);
                if (multiMode) {
                    selectedCoupons.clear();
                    for (int i = 0; i < listSelected.size(); i++) {
                        if (listSelected.get(i).equals("true")) {
                            selectedCoupons.add(multiCoupons.get(i));
                        }
                    }
                }
                intent.putExtra("coupons", (Serializable) selectedCoupons);
                setResult(2001, intent);
                this.finish();
                break;
            default:
                break;
        }
    }

    private class SingleAdapter
            extends
            BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return singleCoupons.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView == null) {
                view = View.inflate(context, R.layout.om_use_coupon_single_list_item, null);
            } else {
                view = convertView;
            }
            TextView tvCoupon = (TextView) view.findViewById(R.id.tv_om_use_coupon_single_price);
            RadioButton rbCoupon = (RadioButton) view.findViewById(R.id.rb_om_use_coupon_single);

            if (singleCoupons.get(position).getCardPrice() < money && singleCoupons.get(position).getUsePrice() <= money) {
                rbCoupon.setEnabled(true);
                tvCoupon.setText(singleCoupons.get(position).getCardName());
                tvCoupon.setTextColor(Color.parseColor("#323232"));
            } else {
                rbCoupon.setEnabled(false);
                if (singleCoupons.get(position).getUsePrice() == 0) {
                    tvCoupon.setText(singleCoupons.get(position).getCardName() + "（不可用）");
                } else {
                    tvCoupon.setText(singleCoupons.get(position).getCardName() + "（满" + singleCoupons.get(position).getUsePrice() / 100 + "元使用）");
                }
                tvCoupon.setTextColor(Color.parseColor("#cbcbcb"));
            }
            if (position == posi) {
                singleMode = true;
                rbCoupon.setChecked(true);
                //				rbCoupon.setButtonDrawable(R.drawable.om_pay_zhifubao_selected);
            } else {
                rbCoupon.setChecked(false);
                //				rbCoupon.setButtonDrawable(R.drawable.om_pay_zhifubao_unselected);
            }
            return view;
        }

    }

    private class MultiAdapter
            extends
            BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return multiCoupons.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView == null) {
                view = View.inflate(context, R.layout.om_use_coupon_multi_list_item, null);
            } else {
                view = convertView;
            }
            TextView tvCoupon = (TextView) view.findViewById(R.id.tv_om_use_coupon_multi_price);
            CheckBox cbCoupon = (CheckBox) view.findViewById(R.id.cb_om_use_coupon_multi);

            if (listSelected.get(position).equals("true")) {
                multiMode = true;
                cbCoupon.setChecked(true);
                tvCoupon.setText(multiCoupons.get(position).getCardName());
                return view;
            }
            if (singleMode) {
                if (multiCoupons.get(position).getCardPrice() < money && multiCoupons.get(position).getUsePrice() <= money) {
                    tvCoupon.setText(multiCoupons.get(position).getCardName());
                    tvCoupon.setTextColor(Color.parseColor("#323232"));
                    cbCoupon.setEnabled(true);
                    cbCoupon.setChecked(false);
                    return view;
                }
            }
            if (multiCoupons.get(position).getUsePrice() > money) {
                tvCoupon.setText(multiCoupons.get(position).getCardName() + "（满" + multiCoupons.get(position).getUsePrice() / 100 + "元使用）");
                tvCoupon.setTextColor(Color.parseColor("#cbcbcb"));
                cbCoupon.setEnabled(false);
                return view;
            }
            if (multiCoupons.get(position).getCardPrice() < money - discount) {
                tvCoupon.setText(multiCoupons.get(position).getCardName());
                tvCoupon.setTextColor(Color.parseColor("#323232"));
                cbCoupon.setEnabled(true);
                cbCoupon.setChecked(false);
            } else if (!cbCoupon.isChecked()) {
                tvCoupon.setText(multiCoupons.get(position).getCardName() + "（不可用）");
                tvCoupon.setTextColor(Color.parseColor("#cbcbcb"));
                cbCoupon.setEnabled(false);
            }
            return view;
        }

    }

    private class QryCouponsHandler
            extends
            ObjectHttpResponseHandler<List<CouponInfo>> {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode < 1000) {
                Utils.ToastShow(context, "网络错误");
            } else {
                Utils.ToastShow(context, "请求出错");
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<CouponInfo> object, String responseString) {
            Log.i(responseString);
            loadingView.setVisibility(View.GONE);
            llBody.setVisibility(View.VISIBLE);
            //测试数据
//			if (object == null || object.size() == 0)
//			{
//			CouponInfo info0 = new CouponInfo();
//			info0.setCardName("1000元代金券");
//			info0.setCardPrice(100000);
//			info0.setIsOnlyOne("y");
//			info0.setUsePrice(200000);
//			object.add(info0);
//			CouponInfo info1 = new CouponInfo();
//			info1.setCardName("100元代金券");
//			info1.setCardPrice(10000);
//			info1.setIsOnlyOne("y");
//			info1.setUsePrice(100);
//			object.add(info1);
//			CouponInfo info2 = new CouponInfo();
//			info2.setCardName("1元代金券");
//			info2.setCardPrice(100);
//			info2.setIsOnlyOne("y");
//			info2.setUsePrice(500000);
//			object.add(info2);
//			CouponInfo info3 = new CouponInfo();
//			info3.setCardName("50元代金券");
//			info3.setCardPrice(5000);
//			info3.setIsOnlyOne("y");
//			info3.setUsePrice(100);
//			object.add(info3);
//			CouponInfo info4 = new CouponInfo();
//			info4.setCardName("200元代金券");
//			info4.setCardPrice(20000);
//			info4.setIsOnlyOne("n");
//			info4.setUsePrice(100);
//			object.add(info4);
//			CouponInfo info5 = new CouponInfo();
//			info5.setCardName("1元代金券");
//			info5.setCardPrice(100);
//			info5.setIsOnlyOne("n");
//			info5.setUsePrice(300000);
//			object.add(info5);
//			CouponInfo info6 = new CouponInfo();
//			info6.setCardName("2500元代金券");
//			info6.setCardPrice(250000);
//			info6.setIsOnlyOne("n");
//			info6.setUsePrice(300000);
//			object.add(info6);
//			CouponInfo info7 = new CouponInfo();
//			info7.setCardName("200元代金券");
//			info7.setCardPrice(20000);
//			info7.setIsOnlyOne("n");
//			info7.setUsePrice(100);
//			object.add(info7);
//			}
            if (object != null && object.size() > 0) {
                listCoupons.clear();
                listCoupons.addAll(object);
                for (int i = 0; i < listCoupons.size(); i++) {
                    if (listCoupons.get(i).getIsOnlyOne().equals("y")) {
                        singleCoupons.add(listCoupons.get(i));
                    } else {
                        multiCoupons.add(listCoupons.get(i));
                    }
                }

                if (listSelected == null || listSelected.size() == 0) {
                    for (int i = 0; i < multiCoupons.size(); i++) {
                        listSelected.add("false");
                    }
                }
                lvSingle.setAdapter(singleAdapter);
                lvMulti.setAdapter(multiAdapter);
                Utils.setListViewHeightBasedOnChildren(lvSingle, singleAdapter);
                Utils.setListViewHeightBasedOnChildren(lvMulti, multiAdapter);
                singleAdapter.notifyDataSetChanged();
                multiAdapter.notifyDataSetChanged();
                if (singleCoupons.size() == 0) {
                    llSingle.setVisibility(View.GONE);
                }
                if (multiCoupons.size() == 0) {
                    llMulti.setVisibility(View.GONE);
                }
                btnSure.setVisibility(View.VISIBLE);
            } else {
                llBody.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<List<CouponInfo>>() {
            }.getType();
        }
    }

    @Override
    public Handler getUIHandler() {
        return handler;
    }
}
